#!/usr/bin/env bash

PANEL_FIFO=/tmp/panel-fifo
PANEL_WM_NAME=bspwm_panel
geo="1920x28+0+10"
f1="drift:style=Regular:size=9"
f2="*-siji-*-*-*--10-*"

color0='#002f343f'
color8='#444A57'
color1='#BF616A'
color9='#BF616A'
color2='#A3BE8C'
color10='#A3BE8C'
color3='#ff9481'
color11='#EBCB8B'
color4='#81A1C1'
color12='#81A1C1'
color5='#B48EAD'
color13='#B48EAD'
color6='#88C0D0'
color14='#88C0D0'
color7='#e1e1e1'
color15='#e7e8eb'

brdr="%{U$color0}%{+u}%{+o}"
calendar="%{A:$HOME/.config/bspwm/dzen_cal:}"

[ -e "${PANEL_FIFO}" ] && rm "${PANEL_FIFO}"
mkfifo "${PANEL_FIFO}"

icon(){
	case $1 in
		0) echo "%{B$color4}%{F$color0}${calendar} $(printf '%b' "\ue225") %{A}%{B-}%{F-}" ;;
		1) echo "%{B$color3}%{F$color0} $(printf '%b' "\ue018") %{B-}%{F-}" ;;
	esac
}

get_clock() 
{
    while true; do
        local clock="$(date +'%H:%M')"
        echo "CLOCK %{B$color15}%{F$color0} ${clock} %{B-}%{F-}"
        sleep 15
    done
}

get_date(){
	while true; do
		local day="$(date +'%a - %b %d, %Y')"
		echo "DATE %{B$color15}%{F$color0} ${day} %{B-}%{F-}"
		sleep 60
	done
}

# Just to make sure there is no double process
killall -9 lemonbar xdo get_clock get_date

# Echo every modules to PANEL_FIFO
get_clock > "${PANEL_FIFO}" &
get_date > "${PANEL_FIFO}" &

loop(){
while read -r line; do
    case $line in
        CLOCK*)
            fn_time="${line#CLOCK }"
            ;;
		DATE*)
			fn_date="${line#DATE }"
			;;
    esac
    printf "%s\n" "${brdr}%{r}$(icon 0)${fn_date}%{O10}$(icon 1)${fn_time}%{O10}"
done
}

loop < "${PANEL_FIFO}" | lemonbar -b -g "${geo}" -f "${f1}" -f "${f2}" \
-B "$color0" -F "$color15" -u 4 -n "$PANEL_WM_NAME"| sh &

sleep 0.5
# Trigger the PANEL_FIFO to make it instantly refreshed after bspwmrc reloaded
echo "dummy" > "$PANEL_FIFO"

sleep 0.5
# Rule the panel to make it hiding below fullscreen window
# I add 'sleep 0.5' to avoid xdo executed before the Lemonbar fully loaded
wid=$(xdo id -a "$PANEL_WM_NAME")
xdo above -t "$(xdo id -N Bspwm -n root | sort | head -n 1)" "$wid"

# Don't close this process
wait
